/**
 * menkor.com Inc.
 * Copyright (c) 2012-2019 All Rights Reserved.
 */
package com.blueskykong.concurrency.concurrent;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author keets
 * @date 2019-10-10.
 */
public class CountDownLatchTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        final CountDownLatch latch = new CountDownLatch(2);
        System.out.println("主线程开始执行…… ……");
        //第一个子线程执行
        ExecutorService es1 = Executors.newSingleThreadExecutor();
        es1.execute(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("子线程：" + Thread.currentThread().getName() + "执行");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            latch.countDown();
        });
        es1.shutdown();

        //第二个子线程执行
        ExecutorService es2 = Executors.newSingleThreadExecutor();
        Future f = es2.submit((Callable) () -> {
            System.out.println("Asynchronous Callable");
            Thread.sleep(3000);
            System.out.println("子线程：" + Thread.currentThread().getName() + "执行");
            latch.countDown();
            return "===== Callable Result";
        });
        System.out.println("get future : "+f.get());
        es2.shutdown();
        System.out.println("等待两个线程执行完毕…… ……");
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("两个子线程都执行完毕，继续执行主线程");
    }
}
